package com.spark.lola.controller.logistics;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.feign.GdsFeignService;
import com.spark.lola.logistics.constant.LogisticsConstant;
import com.spark.lola.logistics.entity.OrderInfo;
import com.spark.lola.logistics.entity.OrderProduct;
import com.spark.lola.logistics.mapper.LogisticsOrderInfoMapper;
import com.spark.lola.logistics.mapper.LogisticsOrderProcessMapper;
import com.spark.lola.logistics.mapper.LogisticsOrderProductMapper;
import com.spark.lola.logistics.request.OrderInfoSaveRequest;
import com.spark.lola.logistics.request.OtherOrderSaveRequest;
import com.spark.lola.logistics.request.UpdateOrderLocationRequest;
import com.spark.lola.logistics.service.DriverInfoService;
import com.spark.lola.logistics.service.LogisticsOrderInfoService;
import com.spark.lola.logistics.vo.OrderInfoVo;
import com.spark.lola.support.api.entity.EnterpriseTokenUser;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.entity.QueryParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author: Zhi-peng wang
 * @date: 2020/05/21 13:56
 **/
@RestController
@RequestMapping(value = "/api/logistics/order", produces = "application/json;charset=utf-8")
@Api(value = "/api/logistics/order", tags = "货运单接口")
public class LogisticsOrderController {

    @Autowired
    private LogisticsOrderInfoService logisticsOrderInfoService;

    @Autowired
    private LogisticsOrderInfoMapper logisticsOrderInfoMapper;

    @Autowired
    private LogisticsOrderProductMapper logisticsOrderProductMapper;

    @Autowired
    private LogisticsOrderProcessMapper logisticsOrderProcessMapper;

    @Autowired
    private DriverInfoService driverInfoService;

    @Autowired
    private GdsFeignService gdsFeignService;

    @ApiOperation(value = "分页查询货运单")
    @RequestMapping(value = "/findBy", method = RequestMethod.POST)
    public ResponseBean findPage(@RequestBody QueryParam<OrderInfoVo> queryParam, @SessionAttribute EnterpriseTokenUser<?> tokenUser) {
        if (CollectionUtils.isEmpty(queryParam.getQueryList())) {
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setKey("o.status");
            queryCondition.setOper("!=");
            queryCondition.setValue(LogisticsConstant.OrderStatus.ALREADY_INVALID);
            queryParam.getQueryList().add(queryCondition);
        }
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setKey("o.creatorId");
        queryCondition.setOper("=");
        queryCondition.setValue(tokenUser.getShiroUser().getId());
        queryParam.getQueryList().add(queryCondition);
        IPage<OrderInfoVo> orderInfoVoIPage = logisticsOrderInfoService.findPage(queryParam);
        List<OrderInfoVo> orderInfoVoList = orderInfoVoIPage.getRecords();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orderInfoVoList.forEach(orderInfoVo -> {
            // 获取货品
            List<OrderProduct> orderProductList = logisticsOrderProductMapper.findByOrderId(orderInfoVo.getId());
            StringBuilder label = new StringBuilder();
            if (!CollectionUtils.isEmpty(orderProductList)) {
                for (int i = 0; i < orderProductList.size(); i++) {
                    label.append(orderProductList.get(i).getName()).append("，").append(orderProductList.get(i).getWeight()).append("吨");
                    if (i < orderProductList.size() - 1) {
                        label.append("|");
                    }
                }
            }
            orderInfoVo.setLabel(label.toString());
            // 获取时间
//            Date date = logisticsOrderProcessMapper.findCreateTimeNewest(orderInfoVo.getId(), orderInfoVo.getStatus(), LogisticsConstant.ProcessFlag.NEWEST);
            orderInfoVo.setStatusTime("创建日期：" + dateFormat.format(orderInfoVo.getCreateTime()));
        });
        orderInfoVoIPage.setRecords(orderInfoVoList);
        return ResponseBean.success(orderInfoVoIPage);
    }

    @ApiOperation(value = "查询货品列表")
    @RequestMapping(value = "/product", method = RequestMethod.POST)
    public ResponseBean product() {
        return ResponseBean.success(gdsFeignService.findProductVo());
    }

    @ApiOperation(value = "回头车匹配地址")
    @RequestMapping(value = "/matchToOrderLocation", method = RequestMethod.POST)
    public ResponseBean matchToOrderLocation(@SessionAttribute EnterpriseTokenUser<?> tokenUser) {
        return ResponseBean.success(logisticsOrderInfoService.matchToOrderLocation(tokenUser.getShiroUser().getId()));
    }

    @ApiOperation(value = "获取货运单详情")
    @ApiImplicitParam(name = "orderId", value = "货运单id", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "/findInfo/{orderId}", method = RequestMethod.POST)
    public ResponseBean findInfo(@PathVariable long orderId, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        if (orderId != 0) {
            orderInfo = logisticsOrderInfoService.findInfo(orderId);
        } else {
            orderInfo.setCarId(driverInfoService.findCarId(tokenUser.getShiroUser().getId()));
        }
        return ResponseBean.success(orderInfo);
    }

    @ApiOperation(value = "添加/修改货运单")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean save(@RequestBody OrderInfoSaveRequest orderInfoSaveRequest, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoSaveRequest, orderInfo);
        orderInfo.setCreatorId(tokenUser.getShiroUser().getId());
        orderInfo.setCreator(tokenUser.getShiroUser().getRealName());
        orderInfo.setUpdator(tokenUser.getShiroUser().getRealName());
        return ResponseBean.success(logisticsOrderInfoService.saveOrder(orderInfo, tokenUser.getShiroUser()));
    }

    @ApiOperation(value = "添加/修改外调车单")
    @RequestMapping(value = "/saveOther", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean saveOther(@RequestBody OtherOrderSaveRequest otherOrderSaveRequest, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(otherOrderSaveRequest, orderInfo);
        orderInfo.setCreatorId(tokenUser.getShiroUser().getId());
        orderInfo.setCreator(tokenUser.getShiroUser().getRealName());
        orderInfo.setUpdator(tokenUser.getShiroUser().getRealName());
        return ResponseBean.success(logisticsOrderInfoService.saveOrder(orderInfo, tokenUser.getShiroUser()));
    }

    @ApiOperation(value = "创建空货运单")
    @RequestMapping(value = "/addEmpty", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addEmpty(@RequestBody OrderInfoSaveRequest orderInfoSaveRequest, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(orderInfoSaveRequest, orderInfo);
        orderInfo.setCreatorId(tokenUser.getShiroUser().getId());
        orderInfo.setCreator(tokenUser.getShiroUser().getRealName());
        orderInfo.setUpdator(tokenUser.getShiroUser().getRealName());
        return ResponseBean.success(logisticsOrderInfoService.saveEmptyOrder(orderInfo, tokenUser.getShiroUser()));
    }

    @ApiOperation(value = "修改货运单地址")
    @RequestMapping(value = "/saveLocation", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean saveLocation(@RequestBody UpdateOrderLocationRequest updateOrderLocationRequest, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        OrderInfo orderInfo = new OrderInfo(updateOrderLocationRequest);
        orderInfo.setVersion(logisticsOrderInfoMapper.findVersionById(orderInfo.getId()));
        logisticsOrderInfoService.updateById(orderInfo);
        return ResponseBean.success();
    }

    @ApiOperation(value = "删除货运单")
    @ApiImplicitParam(name = "orderId", value = "货运单id", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "/del/{orderId}", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean del(@PathVariable long orderId, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        logisticsOrderInfoService.deleteOrder(orderId, tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "取消货运单")
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean cancel(@RequestBody JSONObject jsonObject, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        Long orderId = jsonObject.getLong("orderId");
        String msg = jsonObject.getString("msg");
        if (orderId == null) {
            return ResponseBean.error("参数为空");
        }
        logisticsOrderInfoService.cancel(orderId, msg, tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "货运单发货")
    @RequestMapping(value = "/shipments", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean shipments(@RequestBody JSONObject jsonObject, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        Long orderId = jsonObject.getLong("orderId");
        String credentials = jsonObject.getString("credentials");
        String remark = jsonObject.getString("remark");
        int isEmpty = jsonObject.getIntValue("isEmpty");
        if (isEmpty == LogisticsConstant.OrderIsEmpty.NO) {
            if (orderId == null || credentials == null) {
                return ResponseBean.error("参数为空");
            }
        } else {
            if (orderId == null) {
                return ResponseBean.error("参数为空");
            }
        }
        logisticsOrderInfoService.shipments(orderId, credentials, remark, tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "货运单收货")
    @RequestMapping(value = "/receiving", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean receiving(@RequestBody JSONObject jsonObject, @SessionAttribute EnterpriseTokenUser<?> tokenUser) throws Exception {
        Long orderId = jsonObject.getLong("orderId");
        String credentials = jsonObject.getString("credentials");
        int isEmpty = jsonObject.getIntValue("isEmpty");
        if (isEmpty == LogisticsConstant.OrderIsEmpty.NO) {
            if (orderId == null || credentials == null) {
                return ResponseBean.error("参数为空");
            }
        } else {
            if (orderId == null) {
                return ResponseBean.error("参数为空");
            }
        }
        logisticsOrderInfoService.receiving(orderId, credentials, tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "获取绑定运输单")
    @RequestMapping(value = "/map", method = RequestMethod.POST)
    public ResponseBean map(@RequestBody JSONObject jsonObject, @SessionAttribute EnterpriseTokenUser<?> tokenUser) {
        String key = jsonObject.getString("key");
        Integer lineType = jsonObject.getInteger("lineType");
        if (lineType == null) {
            return ResponseBean.error("线路类型不能为空");
        }
        return ResponseBean.success(logisticsOrderInfoService.selectMap(key, tokenUser.getShiroUser().getId(), lineType));
    }

    @ApiOperation(value = "根据采购单创建货运单")
    @ApiImplicitParam(name = "supOrderNo", value = "采购单号", required = true, dataType = "string", paramType = "path")
    @RequestMapping(value = "/matchSupOrderInfo/{supOrderNo}", method = RequestMethod.POST)
    public ResponseBean matchSupOrderInfo(@PathVariable String supOrderNo) {
        if (StringUtils.isBlank(supOrderNo)) {
            return ResponseBean.error("参数为空");
        }
        OrderInfo orderInfo = logisticsOrderInfoService.matchSupOrderInfo(supOrderNo);
        return ResponseBean.success(orderInfo);
    }

}
